QPainter + QTimer 实现 一个滑动按钮效果 您所在的位置:网站首页 qt 按钮设置颜色 QPainter + QTimer 实现 一个滑动按钮效果

QPainter + QTimer 实现 一个滑动按钮效果

2023-05-28 00:36| 来源: 网络整理| 查看: 265

效果图:

 

custombutton.h

#ifndef CUSTOMBUTTON_H #define CUSTOMBUTTON_H #include #include class CustomButton : public QWidget { Q_OBJECT public: explicit CustomButton(QWidget *parent = nullptr); public slots: void onTimeOut(); protected: /* * Q_DECL_OVERRIDE * 防止写了错误的虚函数名称。你可以使用 Q_DECL_OVERRIDE 宏来声明这是一个对虚函数进行定义的方法,来避免上述错误 */ void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; private: bool m_state; QColor m_backgroundColor; QColor m_ellipseColor; QColor m_checkColor; QTimer *m_timer; int m_Ellipse_X; }; #endif // CUSTOMBUTTON_H

custombutton.cpp

#include "custombutton.h" #include #include #include CustomButton::CustomButton(QWidget *parent) : QWidget(parent) ,m_state(false) ,m_backgroundColor(Qt::white) ,m_checkColor(Qt::green), m_ellipseColor(Qt::red), m_Ellipse_X(100) { m_timer = new QTimer(this); connect(m_timer,&QTimer::timeout,this,&CustomButton::onTimeOut); } void CustomButton::onTimeOut() { //每 1 0 毫秒 右移1 if(m_state) { m_Ellipse_X += 1; if(m_Ellipse_X >= 120) m_timer->stop(); } else//每 1 0 毫秒 左移1 { m_Ellipse_X -= 1; if(m_Ellipse_X stop(); } update(); } void CustomButton::paintEvent(QPaintEvent *event) { Q_UNUSED(event);//Q_UNUSED() 没有实质性的作用,用来避免编译器警告 QPainter* paint = new QPainter(this); paint->setRenderHint(QPainter::Antialiasing); QPainterPath path; QColor backgroundColor; QColor ellipseColor; if(m_state) { backgroundColor = m_checkColor; ellipseColor = m_checkColor; paint->drawText(QRectF(100,80,60,30),tr("state:On")); } else { backgroundColor = m_backgroundColor; ellipseColor = m_ellipseColor; paint->drawText(QRectF(100,80,60,30),tr("state:OFF")); } //外圈圆角矩形 paint->setBrush(backgroundColor); path.addRoundedRect(QRectF(100,50,40,20),10,10); paint->drawPath(path); //内圈圆 paint->setBrush(ellipseColor); paint->drawEllipse(QRectF(m_Ellipse_X,49,21,21)); } void CustomButton::mousePressEvent(QMouseEvent *event) { if(isEnabled()) { if(event->button() & Qt::LeftButton) event->accept(); } else event->ignore(); } void CustomButton::mouseReleaseEvent(QMouseEvent *event) { if(isEnabled()) { if(event->type() == QMouseEvent::MouseButtonRelease && event->button() == Qt::LeftButton) { event->accept(); m_state = !m_state; m_timer->start(10); } } else { event->ignore(); } }

我这里就是简单了写了一下,滑动块的位置和颜色都给写死了。

思路的话就是当触发鼠标释放事件时 触发定时器 然后定时器的槽函数内做的就是移动内圈圆的x坐标

这样会呈现出滑动的效果。

 进群领取qt开发学习资料以及技术交流  在下方↓↓↓↓↓↓↓↓


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有